﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StockCommon;
using StockImport.dataimport.otc.dailyindex;
using StockImport.TaskLog;
using System.Data.OleDb;
using StockImport.dataimport.tse.categoryupdate;
using StockImport.dataimport.otc;
using System.IO;
using StockPostProcessLib;
using DevExpress.XtraCharts;
using StockCommon.data;
using System.Drawing.Imaging;
using StockImageLib;
using StockCommon.formula;
using StockCommon.data.TradeDetail;
using System.Drawing.Drawing2D;
using StockImport.dataimport.basicdata;
using StockCommon.data.bid5;

namespace Bid5Stock
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            initCombo();
            //initChart();

            //FillWeekIndexVolume(chartStockWeekIndexVolumeSimple1.MainChart, "2311");
            //StockImageGenerator g = new StockImageGenerator();
            //g.FillDailyIndexVolume(chartControl2, "2340", 300);
            //exportToImage(chartControl1, @"d:\weekimage\2331.jpg");
        }

        private void exportToImage(ChartControl chartControl1, string p)
        {
            int pos=p.LastIndexOf("\\");
            String path=p.Substring(0,pos);
            Directory.CreateDirectory(path);
            chartControl1.ExportToImage(p, ImageFormat.Jpeg);
        }

        protected void FillWeekIndexVolume(ChartControl chart, String code)
        {
            
            Series indexSeries = chart.Series["指數"];
            Series volumeSeries = chart.Series["成交量"];

            CandleStickSeriesView candleStickSeriesView = (CandleStickSeriesView)indexSeries.View;
            SideBySideBarSeriesView sideBySideBarSeriesView = (SideBySideBarSeriesView)volumeSeries.View;




            indexSeries.Points.Clear();
            volumeSeries.Points.Clear();
            
            //Load Data
             List<WeekIndexAndVolume> datas=StockDataModule.getWeekIndexAndVolume(code);
             int sz = datas.Count;

             SeriesPoint[] stockIndex = new SeriesPoint[sz];
             SeriesPoint[] stockVolume = new SeriesPoint[sz];
            //		DateTime dateTime = DateTime.Parse(arg, DateTimeFormatInfo.InvariantInfo); 
            DateTime dt=DateTime.Now;
            Dictionary<int, StockDataModule.WeekStartEnd> weekToDay = StockDataModule.getWeekToDay();
            double prev = 0;
            double curend=0;
            
             for (int i = 0; i < sz; i++)
             {
                 WeekIndexAndVolume data=datas[i];
                 dt=weekToDay[(int)data.YearWeekKey].startDay;

                 stockIndex[i] = new SeriesPoint(dt, new double[] { (double)data.最低價, (double)data.最高價, (double)data.開盤價, (double)data.收盤價 });
                 stockVolume[i]=new SeriesPoint(dt, new double[] { (double)data.成交股數});
                 curend = (double)data.收盤價;
                 if ((curend - prev) >= 0)
                    stockVolume[i].Tag = "+";
                 else
                     stockVolume[i].Tag = "-";
                 prev = curend;
             }
             indexSeries.Points.AddRange(stockIndex);
             volumeSeries.Points.AddRange(stockVolume);

             DevExpress.XtraCharts.XYDiagram diagram =(XYDiagram)chart.Diagram;


             int w = 160;
            int curyk =(int)(datas[sz - 1].YearWeekKey);
            int minyk=StockDataModule.getOffsetYearWeekKey(curyk,-w+1);
            int maxyk=StockDataModule.getOffsetYearWeekKey(curyk,1);
            DateTime minDate=weekToDay[minyk].startDay;
            DateTime maxDate=weekToDay[maxyk].startDay;

            diagram.AxisX.Range.Auto = false;

            diagram.AxisX.DateTimeGridAlignment = DevExpress.XtraCharts.DateTimeMeasurementUnit.Week;
            diagram.AxisX.DateTimeMeasureUnit = DevExpress.XtraCharts.DateTimeMeasurementUnit.Week;

            diagram.AxisX.Range.MaxValue=maxDate;
            diagram.AxisX.Range.MinValue=minDate;

            chart.Refresh();
            
        }
        protected void initChart()
        {

        }
        protected void initCombo()
        {

            ((System.ComponentModel.ISupportInitialize)(this.mruEdit1.Properties)).BeginInit();

            List<String> ll=StockManager.getStockCodeLike("");
            mruEdit1.Properties.Items.AddRange(ll);
            ((System.ComponentModel.ISupportInitialize)(this.mruEdit1.Properties)).EndInit();
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
         //   CalenderHelper.makeCalendar(DateTime.Parse("2004/02/11"), DateTime.Parse("2014/01/01"));
            DateTime dt = DateTime.Now;
            OTC_DailyIndexFetcher fetcher=new OTC_DailyIndexFetcher();
            fetcher.updateToDate(dt, 10);

            OTC_DailyIndexImport oTC_DailyIndexImport = new OTC_DailyIndexImport();
            oTC_DailyIndexImport.updateToDate(dt);

             UpdateScheduleNaviServices.UpdateSBDetail();
            OTC_DailyIndexImport.logState(DateTime.Parse("2012/09/24"));
            UpdateScheduleNaviServices.Update_TseCount();
            UpdateScheduleNaviServices.Update_OtcCount();

        }

        
        private void button2_Click(object sender, EventArgs e)
        {
            Otc_CategoryUpdater updater = new Otc_CategoryUpdater();
            updater.processIndustyType(DateTime.Now);
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            StockDataClassesDataContext context = LinqAgent.getContext();
            List<String> allCodes = context.ExecuteQuery<String>("select 證券代號 from StockDaily where StockDaily.日期='2012/09/07' order by StockDaily.成交筆數 desc").ToList<String>();
            int segs=0;
            switch (comboBox1.SelectedIndex)
            {
                case -1:
                case 0:
                    segs = 2;
                    break;
                case 1:
                    segs = 3;
                    break;
                case 2:
                    segs = 4;
                    break;
            }
            List<List<String>> allSegs = new List<List<string>>();
            for (int i = 0; i < segs; i++)
            {
                allSegs.Add(new List<string>());
            }

            int sz = allCodes.Count;
            for (int i = 0; i < sz; i++)
            {
                int idx = i % segs;
                allSegs[idx].Add(allCodes[i]);
            }

            for (int i = 0; i < segs; i++)
            {
                String content=String.Join("\r\n",allSegs[i]);
                File.WriteAllText(@"D:\bid5\config\seg"+i.ToString()+".b5l",content);
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            WeekIndexProcesser wp = new WeekIndexProcesser();
            wp.process();
        }

        private void mruEdit1_QueryPopUp(object sender, CancelEventArgs e)
        {

        }

        private void mruEdit1_Validating(object sender, CancelEventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
          DevExpress.XtraEditors.RangeControlRange rangeControlRange1 = new DevExpress.XtraEditors.RangeControlRange();
          DateTime dt = DateTime.Now;
          
            

         StockImageGenerator g=new StockImageGenerator();
          g.FillDailyIndexVolume(chartControl2,"2340",120);
          


        }

        private void button6_Click(object sender, EventArgs e)
        {
            UpDownProcessor p = new UpDownProcessor();
            p.process();

        }

        private void chartControl1_CustomPaint(object sender, CustomPaintEventArgs e)
        {

            Graphics g = e.Graphics;
            HatchBrush brush = new HatchBrush(HatchStyle.ForwardDiagonal,Color.FromArgb(89,255,255,0));
            Point[] pt=new Point[4];
            pt[0]=new Point(0,0);
            pt[1]=new Point(100,0);
            pt[2]=new Point(100,100);
            pt[3]=new Point(0,100);

            g.FillPolygon(brush,pt);

        }

        private void button7_Click(object sender, EventArgs e)
        {
            //StockMinuteTradeDataProvider.getSummary("0050",DateTime.Parse("2012/09/21"));
            StockBid5ImageGenerator g=new StockBid5ImageGenerator();
            g.FillStockBid5(chartControlBid5, "2233", DateTime.Parse("2012/09/21"));
            
            
        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }
    }
}
